def processScale(cropImg):
    '''
    计算比例尺
    :param cropImg: 包含比例尺的图像
    :return: int, 每个比例尺代表的像素个数
    '''
    # 转换成HLS，然后针对L图像进行阈值分割
    dst = cv2.cvtColor(cropImg, cv2.COLOR_RGB2HLS)
    H, L, S = cv2.split(dst)

    # 比例尺为黑色
    ret, L_thresh = cv2.threshold(L, 5, 255, cv2.THRESH_BINARY_INV)

    # 水平模板腐蚀：[1,1,1]，腐蚀垂直方向
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 1))  # 1行3列， rowCount: 1, colCount: 3
    erosion = cv2.erode(L_thresh, kernel, iterations=1)

    open_result = cv2.morphologyEx(L_thresh, cv2.MORPH_OPEN, kernel, iterations=1)

    rowCount = cropImg.shape[0]
    colCount = cropImg.shape[1]
    search_row = 0

    # 查找比例尺的起始行
    for row in range(0, rowCount):
        exit_flag = False
        for col in range(0, colCount):
            if open_result[row, col] != 0:
                search_row = row
                exit_flag = True
                break
        if exit_flag:
            break

    # 查找比例尺的起始列和结束列
    col_left = colCount - 1
    col_right = 0
    for col in range(0, colCount):
        if open_result[search_row, col] != 0:
            if col_left > col:
                col_left = col
            if col_right < col:
                col_right = col

    unit_len = col_right - col_left
    print(f'row:{search_row}, col_left:{col_left}-col_right:{col_right}, len:{unit_len}')

    return unit_len

def extractScaleAndDraw(self):
    '''
    提取图像中的比例尺，并计算每个比例尺代表的像素数
    '''
    scale_contour = None  # 初始化比例尺轮廓

    # 遍历所有轮廓，查找比例尺
    for contour in contours:
        # 计算轮廓的边界框
        x, y, w, h = cv2.boundingRect(contour)
        area = cv2.contourArea(contour)
        print(area)

        if area > 150:  # 过滤掉过小的轮廓
            if x < 100 or y < 100 or x + w > self.soureImg.shape[1] - 100 or y + h > self.soureImg.shape[
                0] - 100:  # 检查轮廓是否位于图像的边缘或角落
                if y > self.soureImg.shape[0] / 2:  # 检查轮廓是否在预期的位置
                    scale_contour = contour  # 将轮廓标记为比例尺

    if scale_contour is None:
        print("未找到比例尺")
    else:
        # 计算比例尺的长度
        x, y, w, h = cv2.boundingRect(scale_contour)
        RoiImg = self.soureImg[y - 30:y + h + 40, x - 20:x + w + 20]

        # 使用 processScale 函数计算比例尺的长度
        scale_length = processScale(RoiImg)  # 每um多少个像素
        print(scale_length)
        self.editUnitPixelNum.setText("{}".format(scale_length))

        # 绘制比例尺轮廓和比例尺信息
        cv2.drawContours(self.soureImg, scale_contour, -1, (0, 255, 0), 2)
